package com.shujia.wyh.udtfdemos;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

public class MyUDTFDemo3 extends GenericUDTF {
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //创建集合,将来存储列构造器（列名）
        ArrayList<String> filedNames = new ArrayList<String>();
        //列的类型
        ArrayList<ObjectInspector> filedObj = new ArrayList<ObjectInspector>();

        filedNames.add("id");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("name");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("phoneNumber");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("flag");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        return ObjectInspectorFactory.getStandardStructObjectInspector(filedNames, filedObj);
    }

    //M1001#xiaohu#S324231212#1,sxq#M1002#0#S2543412432,S21312312412#M1003#wsf#1
    //1001 xiaohu 324231212
    @Override
    public void process(Object[] args) throws HiveException {
        String line = args[0].toString();
        String[] infos = line.split(",");
        String[] str = new String[4];
        for (String info : infos) {
            //M1001#xiaohu#S324231212#1
            String[] infos2 = info.split("#");
            for (String s : infos2) {
                if(s.startsWith("M")){
                    String id = s.substring(1);
                    str[0] = id;
                }else if(s.startsWith("S")){
                    String phoneNumber = s.substring(1);
                    str[2] = phoneNumber;
                }else if("1".equals(s)){
                    str[3] = "支付成功";
                }else if("0".equals(s)){
                    str[3] = "支付失败";
                }else {
                    str[1] = s;
                }
            }
            forward(str);
        }

    }

    @Override
    public void close() throws HiveException {

    }
}
